package com.iqiyi.pps.epg.core.service.encode;

import com.iqiyi.pps.epg.api.model.web.encode.TEncodeServer;
import com.iqiyi.pps.epg.core.dao.encode.EncodeDao;
import com.iqiyi.pps.epg.core.model.encode.EncodeServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuyankui on 15-12-8.
 */

@Service
@Transactional
public class EncodeServiceImpl implements EncodeService {

    public static Logger logger = LoggerFactory.getLogger(EncodeServiceImpl.class);
    @Autowired
    private EncodeDao encodeDao;


    public Long saveEncode(TEncodeServer entity) {

        try {

            long startTime = System.currentTimeMillis();
            EncodeServer encodeServer = new EncodeServer();
            encodeServer.setOutputSignal(entity.getOutputSignal());
            encodeServer.setInputSignal(entity.getInputSignal());
            encodeServer.setModifyTime(new Timestamp(Long.valueOf(entity.getModifyTime())));
            encodeServer.setCreateTime(new Timestamp(Long.valueOf(entity.getCreateTime())));
            encodeServer.setSignalDesc(entity.getSignalDesc());
            encodeServer.setServerIp(entity.getServerIp());
            encodeServer.setStatus(entity.getStatus());
            encodeServer.setExtraData(entity.getExtraData());
            encodeServer.setEncodeType(entity.getEncodeType());
            encodeServer.setIsDolby(entity.getIsDolby());
            encodeServer.setAudio(entity.getAudio());

            String delSql = "DELETE FROM encode_server_stat WHERE output_signal = '" + entity.getOutputSignal() + "'";
            encodeDao.getSession().createSQLQuery(delSql).executeUpdate();


            encodeDao.save(encodeServer);

            logger.info("EncodeServiceImpl.saveEncode", delSql);
            logger.info("EncodeServiceImpl.saveEncode", System.currentTimeMillis() - startTime);

            return encodeServer.getId();

        } catch (Exception e) {
            logger.error("[EncodeServiceImpl][saveEncode][exception=]", e);
            return 0L;
        }finally {

        }


    }

    @Override
    public String findInputsignalByOutputsignal(String outputSignal) {
        try {
            List<EncodeServer> encodeServerList = encodeDao.findBy("outputSignal", outputSignal);
            if (null == encodeServerList || encodeServerList.size() == 0) {
                return null;
            } else {
                return encodeServerList.get(0).getInputSignal();
            }
        } catch (Exception e) {
            logger.error("[EncodeServiceImpl][findInputsignalByOutputSignal][outputSignal={}][exception=]", outputSignal, e);
            return null;
        }
    }

    @Override
    public List<TEncodeServer> duBiStreamInfoSuggest(String streamName, int encodeType) {
        StringBuilder sql = new StringBuilder();

        encodeType += 1;

        sql.append("select id, server_ip, signal_desc, input_signal,output_signal,audio from encode_server_stat where output_signal like '%" + streamName + "%' and is_dolby = 1 and encode_type = " + encodeType +" and status > -1 order by id desc limit 10");

        logger.info("duBiStreamInfoSuggest sql: select id, server_ip, signal_desc, input_signal,output_signal from encode_server_stat where output_signal like '%" + streamName + "%' order by id desc limit 10");

        List result = encodeDao.getSession().createSQLQuery(sql.toString()).list();


        List<TEncodeServer> ret = new ArrayList<>();
        for (Object single : result) {
            Object[] obj = (Object[]) single;
            TEncodeServer temp = new TEncodeServer();
            temp.setId((Long.valueOf(obj[0].toString())));
            temp.setServerIp((String) obj[1]);
            temp.setSignalDesc((String) obj[2]);
            temp.setInputSignal((String) obj[3]);
            temp.setOutputSignal((String) obj[4]);
            temp.setAudio((String) obj[5]);
//            temp.setStatus(Integer.parseInt(obj[5].toString()));

            ret.add(temp);
        }
        return ret;

    }

    @Override
    public List<TEncodeServer> h265StreamInfoSuggest(String streamName) {
        StringBuilder sql = new StringBuilder();

        sql.append("select id, server_ip, signal_desc, input_signal,output_signal  from encode_server_stat where output_signal like '%" + streamName + "%' and is_dolby = 0 and status > -1 and encode_type = 2 order by id desc limit 10");

        logger.info("h265StreamInfoSuggest sql: select id, server_ip, signal_desc, input_signal,output_signal from encode_server_stat where output_signal like '%" + streamName + "%' order by id desc limit 10");

        List result = encodeDao.getSession().createSQLQuery(sql.toString()).list();


        List<TEncodeServer> ret = new ArrayList<>();
        for (Object single : result) {
            Object[] obj = (Object[]) single;
            TEncodeServer temp = new TEncodeServer();
            temp.setId((Long.valueOf(obj[0].toString())));
            temp.setServerIp((String) obj[1]);
            temp.setSignalDesc((String) obj[2]);
            temp.setInputSignal((String) obj[3]);
            temp.setOutputSignal((String) obj[4]);
//            temp.setStatus(Integer.parseInt(obj[5].toString()));

            ret.add(temp);
        }
        return ret;
    }

    @Override
    public EncodeServer getByOutputsignal(String outputSignal) {
        List<EncodeServer> encodeServerList = encodeDao.findBy("outputSignal", outputSignal);

        EncodeServer result = null;

        if(encodeServerList.size() > 0) {
            result = encodeServerList.get(0);
        }

        return result;
    }
}
